#include <vector>
#include <deque>

using std::deque;
using std::vector;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        deque<TreeNode*> q;
        vector<vector<int>> ret;
        if (root != nullptr) {
            q.push_back(root);
        }
        bool order = true;
        int count = 1;
        TreeNode* tmp;
        vector<int> v;
        while (!q.empty()) {
            if (order) {
                tmp = q.front();
                q.pop_front();
                if (tmp->left != nullptr) {
                    q.push_back(tmp->left);
                }
                if (tmp->right != nullptr) {
                    q.push_back(tmp->right);
                }
            }
            else {
                tmp = q.back();
                q.pop_back();
                if (tmp->right != nullptr) {
                    q.push_front(tmp->right);
                }
                if (tmp->left != nullptr) {
                    q.push_front(tmp->left);
                }
            }
            count--;
            v.push_back(tmp->val);
            if (count == 0) {
                count = q.size();
                order = !order;
                ret.push_back(v);
                if (count > 0) {
                    v = vector<int>();
                }
            }
        }
        return ret;
    }
};